package cn.bincker.csustcj.edu;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class DefaultCookieJar implements CookieJar {
    private final List<Cookie> cookies = new ArrayList<>();
    @NotNull
    @Override
    public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
        return cookies.stream().filter(cookie -> cookie.matches(httpUrl)).toList();
    }

    @Override
    public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
        var additional = new ArrayList<Cookie>();
        for (Cookie c : list) {
            boolean flag = false;
            for (int i = 0; i < cookies.size(); i++) {
                Cookie cookie = cookies.get(i);
                if (c.name().equals(cookie.name()) && c.domain().equals(cookie.domain()) && c.path().equals(cookie.path())) {
                    cookies.set(i, c);
                    flag = true;
                    break;
                }
            }
            if (!flag){
                additional.add(c);
            }
        }
        cookies.addAll(additional);
    }
}
